package com.wolfking.jeesite.event;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wolfking.jeesite.entity.SignEvent;
import lombok.*;
import org.springframework.context.ApplicationEvent;

import javax.servlet.http.Cookie;
import java.util.Date;
import java.util.Map;

@Getter
@Setter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public abstract class AbstractSignEvent extends ApplicationEvent {


    protected static final Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();

    private Integer userId;

    private String url;

    private Map<String, Object> parameters;

    private Map<String, String> headers;

    private Map<String, Cookie> cookies;

    private String httpMethod;

    public AbstractSignEvent(Object source) {
        super(source);
    }


    public SignEvent convert2SignEvent() {
        SignEvent signEvent = new SignEvent();
        signEvent.setUrl(url);
        signEvent.setUserId(userId);
        signEvent.setHeaders(gson.toJson(headers));

        Map<String, Object> newParameters = Maps.newHashMap();
        parameters.forEach((k, v) -> {
            if (k.startsWith("sql.")) {
                newParameters.put(k.substring(4), v);
            } else {
                newParameters.put(k, v);
            }
        });
        signEvent.setParameters(gson.toJson(newParameters));
        signEvent.setCookies(gson.toJson(cookies));
        signEvent.setHttpMethod(httpMethod);
        signEvent.setCreateTime(new Date());
        signEvent.setUpdateTime(new Date());
        signEvent.setVersion(0);
        signEvent.setEvent(getClass().getName());
        return signEvent;
    }
}
